package com.cmge.ad.service.impl;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.cmge.ad.mapper.ArticleMapper;
import com.cmge.ad.model.Article;
import com.cmge.ad.model.ArticleStore;
import com.cmge.ad.model.Menu;
import com.cmge.ad.model.SiteCategory;
import com.cmge.ad.service.ArticleService;
import com.cmge.ad.util.FileUtil;
import com.cmge.ad.util.Pager;
import com.cmge.ad.util.SuprUtil;
import com.cmge.ad.util.context.ServletContextUtil;

@Service
@Transactional(isolation=Isolation.DEFAULT,rollbackFor=Exception.class)
public class ArticleServiceImpl implements ArticleService{
	
	public static final Logger logger = Logger.getLogger(ArticleServiceImpl.class);
	
	@Autowired
	private ArticleMapper articleMapper;
	
	@Override
	public void getArticleStoreList(Pager<ArticleStore> pager, HashMap<String, Object> paramMap) {
		int count = articleMapper.getArticleStoreCount(paramMap);
		pager.setTotalCount(count);
		if(count > 0){
			paramMap.put("start", pager.getStart());
			paramMap.put("limit", pager.getLimit());
			List<ArticleStore> appList = articleMapper.getArticleStoreList(paramMap);
			pager.setRows(appList);
		}
	}
	
	@Override
	public int getArticleStoreCount() {
		return articleMapper.getArticleStoreSum();
	}
	
	@Override
	public void getArticleList(Pager<Article> pager, HashMap<String, Object> paramMap,HttpServletRequest request) {
		int count = articleMapper.getArticleCount(paramMap);
		pager.setTotalCount(count);
		if(count > 0){
			paramMap.put("start", pager.getStart());
			paramMap.put("limit", pager.getLimit());
			List<Article> articleList = articleMapper.getArticleList(paramMap);
			
			// 图片地址
			if(!SuprUtil.isEmptyCollection(articleList)){
				String path = request.getContextPath();
				String basePath = request.getScheme() + "://"
						+ request.getServerName() + ":" + request.getServerPort()
						+ path;
				
				for(Article article : articleList){
					if(article.getType() == 2 && !StringUtils.isEmpty(article.getLocationUrl())){
						article.setLocationUrl(basePath+article.getLocationUrl());
					}
				}
			}
			
			pager.setRows(articleList);
		}
	}
	
	@Override
	public List<Menu> getAllArticleMenu() {
		return articleMapper.getAllArticleMenu();
	}
	
	@Override
	public ArticleStore getArticleStoreInfoById(String id) {
		return articleMapper.getArticleStoreInfoById(id);
	}
	
	@Override
	public String getArticleStoreId(ArticleStore article) {
		return articleMapper.getArticleStoreId(article);
	}
	
	@Override
	public String getArticleId(Article article) {
		return articleMapper.getArticleId(article);
	}
	
	@Override
	public Article getArticleInfoById(String id) {
		return articleMapper.getArticleInfoById(id);
	}
	
	@Override
	public void deleteArticleStoreById(Integer id) {
		articleMapper.deleteArticleStoreById(id);
	}
	
	@Override
	public void syncArticleStore(Integer id,Integer menuId,Integer hot) {
		HashMap<String,Object> param = new HashMap<String,Object>();
		param.put("id", id);
		param.put("menuId", menuId);
		
		if(null == hot){
			param.put("hot", 0);
		}else{
			param.put("hot", hot.intValue());
		}
		
		articleMapper.syncArticleStore(param);
		articleMapper.syncArticleStoreStatue(id);
	}
	
	@Override
	public boolean existSyncArticle(Integer id) {
		int count = articleMapper.existSyncArticle(id);
		return count > 0 ? true : false;
	}
	
	@Override
	public List<ArticleStore> getSyncArticleList(int size) {
		return articleMapper.getSyncArticleList(size);
	}
	
	@Override
	public void addArticle(ArticleStore article) {
		articleMapper.addArticle(article);
	}
	
	@Override
	public void deleteSyncArticle(ArticleStore article) {
		articleMapper.deleteSyncArticle(article);
	}
	
	@Override
	public void updateArticleStoreStatue(ArticleStore article) {
		articleMapper.updateArticleStoreStatue(article);
	}
	
	@Override
	public List<Menu> getArticleChildMenu() {
		return articleMapper.getArticleChildMenu();
	}
	
	@Override
	public void autoSyncArticle(int size) {
		// 查询段子所有分类
		List<Menu> menuList = articleMapper.getArticleMenuList();
		for(Menu menu : menuList){
			HashMap<String,Object> param = new HashMap<String,Object>();
			param.put("menu", menu);
			param.put("size", size);
			// 查询源站地址数据
			List<ArticleStore> storeList = articleMapper.getMenuArticleStoreList(param);
			if(!SuprUtil.isEmptyCollection(storeList)){
				for(ArticleStore store : storeList){
					// 插入到同步中间表
					syncArticleStore(store.getId(), menu.getId(), null);
				}
			}
		}
	}
	
	@Override
	public void syncArticle(int size) {
		List<ArticleStore> list = getSyncArticleList(size);
		
		logger.info("待同步的段子数量："+(list != null ? list.size() : 0));
		
		// 获取待同步的段子
		if(!SuprUtil.isEmptyCollection(list)){
			for(ArticleStore article : list){
				int width = 0,hight = 0;
				String locationUrl = "";
				// 如果有图片 则下载图片 并获取图片的宽高
				if(article.getType() == 2){
					try {
						String fileName = ServletContextUtil.getContext().getRealPath("/")+"upload/";
						String file = article.getMinImageUrl();
						int index = file.toLowerCase().lastIndexOf(".jpg");
						if(index < 0){
							index = file.toLowerCase().lastIndexOf(".png");
						}
						
						String pref = "";
						
						if(index < 0){
							pref = ".jpg";
						}else{
							pref = file.substring(index, file.length());
						}
						
						String post = System.currentTimeMillis() + pref;
						fileName = fileName + post;
						
						FileUtil.downloadFile(article.getMinImageUrl(),fileName);
						
						File picture = new File(fileName);  
				        BufferedImage sourceImg =ImageIO.read(new FileInputStream(picture));   
						width = sourceImg.getWidth();
						hight = sourceImg.getHeight();
						
						// 保存相对路径
						locationUrl = "/upload/"+post;
					} catch (Exception e) {
						logger.error("获取图片地址宽高异常：【"+article.getMinImageUrl()+"】",e);
						// 从临时表中删除段子
						deleteSyncArticle(article);
						// 更新仓库段子的状态  同步失败
						article.setStatue(2);
						updateArticleStoreStatue(article);
						continue;
					}						
				}
				
				article.setWidth(width);
				article.setHeight(hight);
				article.setLocationUrl(locationUrl);
				// 赞
				article.setZan(new Random().nextInt(1000));
//				// 插入段子表中
				addArticle(article);
//				// 从临时表中删除段子
				deleteSyncArticle(article);
//				// 更新仓库段子的状态  已同步
				article.setStatue(1);
				updateArticleStoreStatue(article);
			}
			
		}
	}

	@Override
	public void saveArticle(Article article) throws FileNotFoundException, IOException {
		if(null != article){
			if(null != article.getMinImageUrl() && !article.getMinImageUrl().equals("")){
				article.setType(2);
				String fileName = article.getMinImageUrl();
				String locationUrl = "/upload" + fileName.substring(fileName.lastIndexOf("/"));
				fileName = ServletContextUtil.getContext().getRealPath("/")+locationUrl;
				File picture = new File(fileName); 
		        BufferedImage sourceImg =ImageIO.read(new FileInputStream(picture));
				int width = sourceImg.getWidth();
				int hight = sourceImg.getHeight();
				article.setLocationUrl(locationUrl);
				article.setWidth(width);
				article.setHeight(hight);
			}else{
				article.setType(1);
			}
			articleMapper.saveArticle(article);
		}
	}

	@Override
	public int delArticle(Integer id) {
		return articleMapper.delArticle(id);
	}
	
	@Override
	public void refreshArticleCache() {
		
	}
	
}
